package com.shiyipicture.shiyipicturebackend.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shiyipicture.shiyipicturebackend.auth.StpKit;
import com.shiyipicture.shiyipicturebackend.constant.UserConstant;
import com.shiyipicture.shiyipicturebackend.enums.UserRoleEnum;
import com.shiyipicture.shiyipicturebackend.exception.BusinessException;
import com.shiyipicture.shiyipicturebackend.exception.ErrorCode;
import com.shiyipicture.shiyipicturebackend.model.dto.space.SpaceAddRequest;
import com.shiyipicture.shiyipicturebackend.model.dto.user.UserQueryRequest;
import com.shiyipicture.shiyipicturebackend.model.entity.User;
import com.shiyipicture.shiyipicturebackend.model.vo.UserLoginVo;
import com.shiyipicture.shiyipicturebackend.model.vo.UserVO;
import com.shiyipicture.shiyipicturebackend.service.SpaceService;
import com.shiyipicture.shiyipicturebackend.service.UserService;
import com.shiyipicture.shiyipicturebackend.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-01-02 17:51:49
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
  implements UserService {

  @Override
  @Transactional
  public long userRegister(String userAccount, String userPassword, String checkPassword) {
    // 1.校验参数
    if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
    }

    if (userAccount.length() < 4) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
    }

    if (userPassword.length() < 8 || checkPassword.length() < 8) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
    }

    if (!userPassword.equals(checkPassword)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入密码不一致");
    }
    // 2.检查用户在数据库中是否存在
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    userQueryWrapper.eq("userAccount", userAccount);
    Long count = this.baseMapper.selectCount(userQueryWrapper);
    if (count > 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
    }
    // 3. 密码一定要加密
    String encryptPassword = getEncryptPassword(userPassword);

    // 4. 插入数据到数据库中

    User user = new User();
    user.setUserAccount(userAccount);
    user.setUserPassword(encryptPassword);
    user.setUserName("十一");
    user.setUserRole(UserRoleEnum.USER.getValue());
    boolean saveResult = this.save(user);
    if (!saveResult) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
    }
    SpaceServiceImpl spaceService = (SpaceServiceImpl) AopContext.currentProxy();
    spaceService.addSpace(new SpaceAddRequest(), user);
    return user.getId();
  }

  @Override
  public UserLoginVo userLogin(String userAccount, String userPassword, HttpServletRequest request) {
    // 1.校验
    // 1.校验参数
    if (StrUtil.hasBlank(userAccount, userPassword)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
    }

    if (userAccount.length() < 4) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号错误");
    }

    if (userPassword.length() < 8) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码错误");
    }
    // 2.对用户的密码进行加密
    String encryptPassword = getEncryptPassword(userPassword);
    // 3.查询数据库中的用户
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    userQueryWrapper.eq("userAccount", userAccount)
      .eq("userPassword", encryptPassword);
    User user = this.baseMapper.selectOne(userQueryWrapper);
    // 4.不存在抛异常
    if (user == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
    }
    // 5.保存用户登录态
    request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);

// 4. 记录用户登录态到 Sa-token，便于空间鉴权时使用，注意保证该用户信息与 SpringSession 中的信息过期时间一致
    StpKit.SPACE.login(user.getId());
    StpKit.SPACE.getSession().set(UserConstant.USER_LOGIN_STATE, user);

    return getLoginUserVo(user);
  }

  /**
   * 获取脱敏类的用户信息
   *
   * @param user
   * @return
   */
  @Override
  public UserLoginVo getLoginUserVo(User user) {
    if (user == null) {
      return null;
    }
    UserLoginVo userLoginVo = new UserLoginVo();
    BeanUtils.copyProperties(user, userLoginVo);
    return userLoginVo;
  }

  @Override
  public UserVO getUserVo(User user) {
    if (user == null) {
      return null;
    }
    UserVO userVo = new UserVO();
    BeanUtils.copyProperties(user, userVo);
    return userVo;
  }

  @Override
  public List<UserVO> getUserVoList(List<User> userList) {
    if (userList.isEmpty()) {
      return new ArrayList<>();
    }
    return userList.stream().map(this::getUserVo).collect(Collectors.toList());
  }


  /**
   * 获取当前登录用户
   *
   * @param request
   * @return
   */
  @Override
  public User getLoginUser(HttpServletRequest request) {
    //判断是否已经登陆
    Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
    User currentUser = (User) userObj;
    if (currentUser == null || currentUser.getId() == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    Long userId = currentUser.getId();
    currentUser = this.getById(userId);
    if (currentUser == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    return currentUser;
  }

  @Override
  public boolean userLogout(HttpServletRequest request) {
    //判断是否已经登陆
    Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
    User currentUser = (User) userObj;
    if (currentUser == null || currentUser.getId() == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
    }
    // 移除登录态
    request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);

    return true;
  }


  @Override
  public String getEncryptPassword(String password) {
    //加盐 混淆密码
    final String SALT = "shiyi";
    return DigestUtils.md5DigestAsHex((SALT + password).getBytes());
  }

  @Override
  public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
    if (userQueryRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
    }
    Long id = userQueryRequest.getId();
    String userAccount = userQueryRequest.getUserAccount();
    String userName = userQueryRequest.getUserName();
    String userProfile = userQueryRequest.getUserProfile();
    String userRole = userQueryRequest.getUserRole();
    String sortField = userQueryRequest.getSortField();
    String sortOrder = userQueryRequest.getSortOrder();
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
    queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
    queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
    queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
    queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
    queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
    return queryWrapper;
  }

  @Override
  public boolean isAdmin(User user) {
    return user != null && user.getUserRole().equals(UserRoleEnum.ADMIN.getValue());
  }

}




